<template>
    <q-page>
        <q-inner-loading visible v-if="articalLoading">
            <q-spinner-gears size="50px" color="primary" />
            <b class="text-primary">数据加载中...</b>
        </q-inner-loading>

        <!-- header -->
        <q-toolbar color="primary">
            <q-toolbar-title shrink class="q-pa-none">
                <q-select inverted hide-underline v-model="currentDays" :options="dayOptions" />
            </q-toolbar-title>
            <q-toolbar-title right>
                <span slot="subtitle" class="text-right">
                    <div>
                        <b>{{this.filteredLength}}</b>个
                    </div>
                    <div>当前筛选</div>
                </span>
            </q-toolbar-title>
        </q-toolbar>

        <q-infinite-scroll :handler="loadMoreData" :offset="100" ref="infiniteScroll">
            <div class="bg-white">
                <div class="q-pa-xs">
                    <q-btn
                        v-for="(catetory,idx) in allCategories"
                        :key="catetory.id + '-' + idx"
                        @click.stop="changeCategory(catetory)"
                        :label="catetory.name"
                        :outline="curCategory !== catetory.key"
                        dense
                        color="primary"
                        class="q-ma-xs"
                    />
                </div>

                <q-item style="padding:0;">
                    <q-search
                        icon="mdi-account-search"
                        class="full-width no-shadow"
                        inverted-light
                        color="grey-2"
                        placeholder="可通过文章标题、分类、tag搜索"
                        autofocus="true"
                        clearable
                        :value="filter"
                        @clear="filterResult('')"
                        @change="filterResult"
                        @input="filterResult"
                    />
                </q-item>
            </div>
            <!-- list -->
            <q-list separator>
                <q-item class="text-primary" v-if="!this.filteredArticals.length && !articalLoading">暂无数据</q-item>
                <artical-item 
                    v-for="(item,idx) in this.filteredArticals" 
                    :key="item.articalid + idx"
                    :item="item" 
                    position="all"/>
            </q-list>
        </q-infinite-scroll>
    </q-page>
</template>

<script>
import ArticalItem from './ArticalItem.vue'

export default {
    name: "PageIndexOffical",
    components: { ArticalItem },
    data() {
        return {
            allCategories: [],
            articals: [],
            curCategory: "all",
            filter: "",
            limit: 200,
            page: 1,
            list: [],
            ids: new Set(),
            articalLoading: true,
            timer: null,
            currentItem: null,
            currentDays: 0,
            dayOptions: [
                { label: '最近24时', value: 1 },
                { label: '最近3天', value: 3 },
                { label: '最近7天', value: 7 },
                { label: '最近15天', value: 15 },
                { label: '所有', value: 0 },
            ],
            filteredLength: 0,
        };
    },
    mounted() {
        this.$api.ui.pageTitle = "公众号管理";
        this.loadCategories();
        this.$refs.scroll && this.$refs.scroll.loadMore();
        this.$api.offical.loadAllTags()
        // this.curCategory = this.$q.sessionStorage.get.item( 'currentCategory' ) || '全部分类'
    },
    methods: {
        loadCategories(page, done) {
            let me = this;
            this.$api.offical.loadCategories(data => {
                // this.loading = false
                // console.log(data);
                this.allCategories = [...data];
            });
        },
        resetList() {
            //   this.$refs && this.$refs.infiniteScroll && this.$refs.infiniteScroll.resume()
            // this.list = this.allAccount.slice(0, this.page * this.limit);
        },
        changeCategory(category) {
            // console.log("category:::", category);
            this.articalLoading = true
            this.filter = "";
            this.curCategory = category.key;
            this.articals = []
            this.$refs.infiniteScroll.reset();
            this.$refs.infiniteScroll.loadMore();
        },
        filterResult(val) {
            if (!!this.timer) {
                clearTimeout(this.timer);
            }

            // let query = val.toLowerCase();
    
            // // if (!query) {
            // //     this.$refs.infiniteScroll.resume();
            // //     this.resetList();
            // //     return;
            // // }

            // // this.$refs.infiniteScroll.stop();

            // // console.log( 'this.filteredArticals', this.filteredArticals )

            this.timer = setTimeout(() => {
                this.filter = val.toLowerCase();
            }, 300);
        },
        changeModified(item) {
            let { articalid, modified, id } = item;
            this.updateArtical(id, { modified }, data => {
                console.log("updated");
            });
        },
        updateArtical(articalid, options, callback) {
            this.$api.offical.updateArticals(articalid, options, callback);
        },
        loadMoreData(page, done) {
            this.$api.offical.loadCategoryArticals(
                this.curCategory,
                page,
                this.limit,
                data => {
                    this.articalLoading = false
                    this.articals.push(...data);
                    this.filteredLength = this.articals.length
                    done( data.length < this.limit )
                }
            );
        },
        formatNumbers(num) {
            let number = "" + num;
            let showStr = "";
            if (number > 99999) {
                showStr = "10w+";
            } else if (number > 9999 && number < 100000) {
                showStr = Math.floor(number / 10000) + "w+";
            } else if (number > 999 && number < 10000) {
                showStr = Math.floor(number / 1000) + "k+";
            } else {
                showStr = number;
            }

            return showStr;
        },
        filterArticalByDays( list ){
            if( !this.currentDays ) {
                this.filteredLength = list.length
                return list
            }
            let _list = list.filter( item => {
                let {publictime} = item
                if( !publictime ) {
                    return false
                }
                let _date = publictime.replace(/\-/g, '/')
                let _dataStr = new Date( _date ).getTime()
                let _timerPast = (Date.now() - _dataStr) / ( 1000 * 86400 )
                return _timerPast < this.currentDays
            })
            this.filteredLength = _list.length
            return _list
        }
    },
    computed: {
        filteredArticals() {
            // console.log( this.articals )
            let category = this.currentCategory;
            let _list = this.articals.filter(item => {
                if (!this.showUnModified) {
                    return true;
                }
                return !item.modified;
            });
            let query = this.filter.toLowerCase();
            if (!query.length) {
                return this.filterArticalByDays(_list);
            }
            // console.log(query);
            _list = this.articals.filter(item => {
                let { accountname, accountid, category, title, tags } = item;
                if (
                    (accountname && accountname.toLowerCase().indexOf(query) >= 0) || //公众号名称
                    (accountid && accountid.toLowerCase().indexOf(query) >= 0) || // 公众号id
                    (title && title.indexOf(query) >= 0) || // 标题
                    (category && category.indexOf(query) >= 0) || // 分类
                    (tags && tags.indexOf(query) >= 0)
                ) {
                    return true;
                }
                return false;
            });
            // console.log(_list);
            return this.filterArticalByDays(_list);;
        }
    }
};
</script>

<style>
.tags_adder {
    display: inline-block;
}
.tags_adder div {
    display: inline-block;
}
.tags_adder div input {
    width: 50px !important;
}
</style>
